package com.example.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * @Classname HttpUtil
 * @Description TODO
 * @Date 2023/4/26 15:06
 * @Created by XiongXiong
 * @Author: X.I.O
 */
public class HttpUtil {

    private static final String USER_AGENT = "Mozilla/5.0";

    /**
     * 发送 POST 请求并获取响应结果
     *
     * @param url        请求地址
     * @param parameters 请求参数（如："name1=value1&name2=value2"），可以为空
     * @return 响应结果字符串
     * @throws IOException
     */
    public static String sendPost(String url, String parameters) throws IOException {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // 设置请求方法和请求头
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        // 发送 POST 请求
        con.setDoOutput(true);
        try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
            if (parameters != null) {
                byte[] postData = parameters.getBytes(StandardCharsets.UTF_8);
                int postDataLength = postData.length;
                con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                con.setRequestProperty("Content-Length", Integer.toString(postDataLength));
                wr.write(postData);
            }
        }

        // 获取响应结果
        StringBuilder response = new StringBuilder();
        try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
            String line;
            while ((line = in.readLine()) != null) {
                response.append(line);
            }
        }

        return response.toString();
    }


    /**
     * 发送 POST 请求并获取响应结果
     *
     * @param url      请求地址
     * @param jsonBody 请求体JSON字符串，例如："{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}"
     * @return 响应结果字符串
     * @throws IOException
     */
    public static String sendPostJson(String url, String jsonBody) throws IOException {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // 设置请求方法和请求头
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

        // 发送 POST 请求
        con.setDoOutput(true);
        try (OutputStream wr = con.getOutputStream()) {
            byte[] postData = jsonBody.getBytes(StandardCharsets.UTF_8);
            int postDataLength = postData.length;
            con.setRequestProperty("Content-Length", Integer.toString(postDataLength));
            wr.write(postData);
        }

        // 获取响应结果
        StringBuilder response = new StringBuilder();
        try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
            String line;
            while ((line = in.readLine()) != null) {
                response.append(line);
            }
        }

        return response.toString();
    }

    /**
     * 发送 POST 请求并获取响应结果
     *
     * @param url         请求地址
     * @param parameters  请求参数，如："name1=value1&name2=value2"，可以为空
     * @param fileParam   文件参数名称
     * @param fileName    文件名
     * @param fileContent 文件内容
     * @return 响应结果字符串
     * @throws IOException
     */
    public static String sendPost(String url, String parameters, String fileParam, String fileName, byte[] fileContent) throws IOException {
        String boundary = "----" + Long.toHexString(System.currentTimeMillis());
        HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();

        // 设置请求方法和请求头
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        // 发送 POST 请求
        con.setDoOutput(true);
        try (DataOutputStream out = new DataOutputStream(con.getOutputStream())) {
            // 写入普通参数
            if (parameters != null) {
                writeStringField(out, boundary, parameters);
            }
            // 写入文件参数
            writeFileField(out, boundary, fileParam, fileName, fileContent);
            // 写入结束标记
            out.writeBytes("--" + boundary + "--\r\n");
            out.flush();
        }

        // 获取响应结果
        try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
            return in.lines().reduce("", String::concat);
        }
    }

    private static void writeStringField(DataOutputStream out, String boundary, String value) throws IOException {
        out.writeBytes("--" + boundary + "\r\n");
        out.writeBytes("Content-Disposition: form-data; name=\"\"");
        out.writeBytes("\r\n\r\n" + value + "\r\n");
    }

    private static void writeFileField(DataOutputStream out, String boundary, String fileParam, String fileName, byte[] fileContent) throws IOException {
        out.writeBytes("--" + boundary + "\r\n");
        out.writeBytes("Content-Disposition: form-data; name=\"" + fileParam + "\"; filename=\"" + fileName + "\"\r\n");
        out.writeBytes("Content-Type: application/octet-stream\r\n\r\n");
        out.write(fileContent);
        out.writeBytes("\r\n");
    }


    public static String sendGet(String url) throws Exception {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // 设置请求方法为 GET
        con.setRequestMethod("GET");

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        return response.toString();
    }
}
